#!/usr/bin/python
# -*- coding: UTF-8 -*-

import openpyxl
import docx
import os
import sys
sys.path.append("..")
from lib.GoogleSearch.GoogleSearch import Search
from lib.Detector.Match import Match_Email, Match_TelphoneNumber, Match_Idcard
from requests import get
from os.path import dirname, abspath

path = dirname(dirname(abspath(__file__)))

def Search_Target(domain_name,num = 100):
	payload = "site:*." + domain_name
	search_result = []
	filetype = ['xls','doc','pdf']
	search_result = search_result + Search(payload)
	for i in filetype:
		payload = "site:*." + domain_name + " filetype:" + i
		search_result = search_result + Search(payload)
	return search_result

def Check_Information_Disclosure(string):
	print("[*] Checking Information Disclosure------------------------------")
	matches = []
	matches = matches + Match_Email(string) + Match_TelphoneNumber(string) + Match_Idcard(string)
	if matches == []:
		return False
	else:
		return matches
 
def Get_File(url):
	global path
	with open(path + "1.temp",'wb+') as file:
		response = get(url)
		file.write(response.content)
	file.close()

def Save_Resutl(list_to_write, url):
	global path
	with open(path + '/output/result.txt','a+') as file:
		file.write('URL : '+ url+'\n\n')
		for text in list_to_write:
			file.write(text + '\n')
	file.close()

def Analyze_XLS(url):
	global path
	print("[*] INFO: Analysis Start. Current_URL: %s"%url)
	Get_File(url)
	os.rename(path + "1.temp", path + "1.xlsx")
	try:
		wb = openpyxl.load_workbook(filename=path + '1.xlsx')
	except ValueError:
		print("[!] WARNING: Failed to open XLS or XLSX file , Skiping")
	tempfile = open(path + 'temp.txt','a+')
	sheets = wb.sheetnames
	for i in range(len(sheets)):
		sheet= wb[(sheets[i])]
		for r in range(1,sheet.max_row+1):
			if r == 1:
				print('\n'+''.join([str(sheet.cell(row=r,column=c).value).ljust(17) for c in range(1,sheet.max_column+1)]),file=tempfile)
			else:
				print(''.join([str(sheet.cell(row=r,column=c).value).ljust(20) for c in range(1,sheet.max_column+1)]),file=tempfile)
	tempfile.close()
	tempfile = open(path + 'temp.txt','r')
	string = tempfile.read()
	tempfile.close()
	os.remove(path + '1.xlsx')
	os.remove(path + 'temp.txt')
	matches = Check_Information_Disclosure(string)
	if matches == False:
		return "SAFE"
	else:
		Save_Resutl(matches,url)
		print("[*] INFO: !!%s!! , Information Disclosure Detected，See result.txt"%url)
		return "UNSAFE"

def Analyze_DOC(url):
	print("[*] INFO: Analysis Start. Current_URL: %s"%url)
	Get_File(url)
	os.rename(path + "1.temp", path + "1.docx")
	try:
		tempfile = docx.Document(path + '1.docx')
	except ValueError:
		print("[!] WARNING: Failed to open DOC or DOCX file , Skiping")
	string = ''
	for para in tempfile.paragraphs:
		string = string + para.text
	os.remove(path + '1.docx')
	matches = Check_Information_Disclosure(string)
	if  matches == False:
		return "SAFE"
	else:
		Save_Resutl(matches,url)
		print("[*] INFO: !!%s!! ,Information Disclosure Detected，See result.txt"%url)
		return "UNSAFE"

def Analyze_PDF(url):
	print("[*] INFO: Analysis Start. Current_URL: %s"%url)
	pass

def Analyze_HTML(url):
	print("[*] INFO: Analysis Start. Current_URL: %s"%url)
	Get_File(url)
	tempfile = open(path + '1.temp','r')
	try:
		string = tempfile.read()
	except UnicodeDecodeError:
		return 0
	tempfile.close()
	os.remove(path + '1.temp')
	matches = Check_Information_Disclosure(string)
	if  matches == False:
		return "SAFE"
	else:
		Save_Resutl(matches,url)
		print("[*] INFO: !!%s!! ,Information Disclosure Detected，See result.txt"%url)
		return "UNSAFE"

def Google_Hacker(domain_name, num = 100):
	search_result = Search_Target(domain_name,num = 100)
	for current_url in search_result:
		if '.xls' in current_url or '.xlsx' in current_url:
			Analyze_XLS(current_url)
		elif '.doc' in current_url or '.docx' in current_url:
			Analyze_DOC(current_url)
		elif '.pdf' in current_url:
			Analyze_PDF(current_url)
		else:
			Analyze_HTML(current_url)


if __name__ == '__main__':
	pass